package com.example.lte.api;

import cn.dev33.satoken.stp.StpUtil;
import com.example.lte.config.BusinessLogic;
import com.example.lte.config.LinuxEnvironmentConfig;
import com.example.lte.config.SysBusinessUnitEnum;
import com.example.lte.config.WindowsEnvironmentConfig;
import com.example.lte.po.*;
import com.example.lte.po.server.ServerInfo;
import com.example.lte.service.ISystemLocalService;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Date;
import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * @author lzh
 * @date 2020/10/22 - 14:21
 */
@RestController
@Api(tags = "练习")
public class LearnApi {
    private  WindowsEnvironmentConfig windowsEnvironmentConfig;

    private  LinuxEnvironmentConfig linuxEnvironmentConfig;


    private ISystemLocalService iSystemLocalService;

    @Autowired
    public void setiSystemLocalService(ISystemLocalService iSystemLocalService) {
        this.iSystemLocalService = iSystemLocalService;
    }

    @Autowired
    public void setWindowsEnvironmentConfig(WindowsEnvironmentConfig windowsEnvironmentConfig) {
        this.windowsEnvironmentConfig = windowsEnvironmentConfig;
    }

    @Autowired
    public void setLinuxEnvironmentConfig(LinuxEnvironmentConfig linuxEnvironmentConfig) {
        this.linuxEnvironmentConfig = linuxEnvironmentConfig;
    }




    @GetMapping("/serverHardInfo")
    @ApiOperation(value = "查看服务器信息",notes = "详细描述-查看服务器信息")
    @BusinessLogic(value = "查看服务器信息",businessUnit = SysBusinessUnitEnum.DEFAULT_UNIT)
    public ServerInfo getInfo() throws Exception {
        StpUtil.checkLogin();

        ServerInfo info = new ServerInfo();
        info.copyTo();
        return info;
    }

    @GetMapping("/html")
    @ApiOperation(value = "获取服务器html字符串",notes = "详细描述-获取服务器html字符串")
    @BusinessLogic(value = "获取服务器html字符串",businessUnit = SysBusinessUnitEnum.DEFAULT_UNIT)
    public TestResp htmlToString() throws IOException {
        StpUtil.checkLogin();
        FileSystemResource resource ;
        StringBuilder result = new StringBuilder();
        Properties props = System.getProperties();
        String os = props.getProperty("os.name");
        if (os.startsWith("Win")) {
            resource = new FileSystemResource(windowsEnvironmentConfig.getFileUploadDir()  + "serverStr.html");
        }else {
            resource = new FileSystemResource(linuxEnvironmentConfig.getFileUploadDir()  + "serverStr.html");
        }



        File file = resource.getFile();
        BufferedReader br = new BufferedReader(new FileReader(file));
        String s = null;
        while ((s = br.readLine()) != null) {
            result.append(s);
        }
        br.close();

        return TestResp.builder()
                .htmlContent(result.toString())
                .time(new Date())
                .build();


    }


    @GetMapping("/getIpAddr")
    public ServerIpAddrInfo getIpAddr() throws InterruptedException, ExecutionException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
        StpUtil.checkLogin();
        return iSystemLocalService.findIpAddr();
    }


    /**
     * 获取用户真实IP地址，不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址。
     * 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值，究竟哪个才是真正的用户端的真实IP呢？
     * 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串
     * <p>
     * 说说这些请求头的意思
     * <p>
     * X-Forwarded-For
     * 这是一个 Squid 开发的字段，只有在通过了HTTP代理或者负载均衡服务器时才会添加该项。
     * 格式为X-Forwarded-For:client1,proxy1,proxy2，一般情况下，第一个ip为客户端真实ip，后面的为经过的代理服务器ip。现在大部分的代理都会加上这个请求头。
     * <p>
     * Proxy-Client-IP/WL- Proxy-Client-IP
     * 这个一般是经过apache http服务器的请求才会有，用apache http做代理时一般会加上Proxy-Client-IP请求头，而WL-Proxy-Client-IP是他的weblogic插件加上的头。
     * <p>
     * HTTP_CLIENT_IP
     * 有些代理服务器会加上此请求头。
     * <p>
     * X-Real-IP
     * nginx代理一般会加上此请求头
     *
     * @param request
     * @return
     */
    @GetMapping("/tip")
    public String getIpAddress(HttpServletRequest request) {
        StpUtil.checkLogin();


        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ip = inet.getHostAddress();
            }
        }
        ///对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        int i = 15;
        String s = ",";
        if (ip != null && ip.length() > i) {
            if (ip.indexOf(s) > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }

        return ip;
    }


    @GetMapping("/device")
    public ReqDevice testDevice(HttpServletRequest request) {
        StpUtil.checkLogin();

        //用户的发起请求的设备
        //Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36
        String userAgent = request.getHeader("user-agent");
        System.out.println(userAgent);
        //解析agent字符串
        UserAgent ua = UserAgent.parseUserAgentString(userAgent);
        //获取浏览器对象
        Browser browser = ua.getBrowser();
        //获取操作系统对象
        OperatingSystem os = ua.getOperatingSystem();

        return ReqDevice.builder()
                .browserEngine(browser.getRenderingEngine().getName())
                .browserName(browser.getName())
                .browserVersion(browser.getVersion(userAgent).getVersion())
                .deviceType(os.getDeviceType().getName())
                .systemName(os.getName())
                .build();

    }


    //--------get请求用@DateTimeFormat指明日期转换格式----------------------------------------------------
    //1.get请求多参数中含有Date的情况
    @GetMapping("/t1")
    public TestReq test1(TestReq req) {
        System.out.println(req.toString());
        return req;
    }


    @GetMapping("/t2")
    //2.get请求-单参数中含有Date的情况
    public Date t2(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date sendTime) {
        System.out.println(sendTime);
        return sendTime;
    }

//---------------------------------------------------------------------------

    //----POST请求的JSON参数中含有Date的情况
    // 用@JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")
    // 指明jackson日期转换格式

    //测试1
    //{
    //    "startDate":"2020-10-11",
    //    "endDate":"2020-10-31"
    //}
    //{
    //    "code": 0,
    //    "msg": "操作成功",
    //    "data": {
    //        "startDate": "2020-10-11",
    //        "endDate": "2020-10-31"
    //    },
    //    "timestamp": 1603350780528
    //}

    // 测试2
    //{
    //    "startDate":"2020-10-11"
    //}
    //{
    //    "code": 9996,
    //    "msg": "参数校验异常",
    //    "data": "endDate 不能为空",
    //    "timestamp": 1603350694443
    //}
    @PostMapping("/t3")
    public TimeReq t3(@RequestBody @Valid TimeReq req) {
        System.out.println(req.toString());
        return req;
    }


}
